#include "../../include/unm.h"
#include <git2.h>
#include <algorithm>
#include <cmath>
#include <fstream>
#include <iostream>

namespace unm {

UniversalNodeManager::UniversalNodeManager() {
    git_libgit2_init();
}

UniversalNodeManager::~UniversalNodeManager() {
    if (repo_) {
        git_repository_free(repo_);
    }
    git_libgit2_shutdown();
}

bool UniversalNodeManager::addNode(const Node& node) {
    if (nodes_.find(node.id) != nodes_.end()) {
        return false; // 节点已存在
    }
    nodes_[node.id] = node;
    
    // 自动发现特征
    discoverFeatures(nodes_[node.id]);
    
    // 分析关系
    analyzeRelations(nodes_[node.id]);
    
    return true;
}

bool UniversalNodeManager::removeNode(const std::string& node_id) {
    auto it = nodes_.find(node_id);
    if (it == nodes_.end()) {
        return false;
    }
    
    // 移除相关的关系
    relations_.erase(
        std::remove_if(relations_.begin(), relations_.end(),
            [&](const Relation& rel) {
                return rel.source_id == node_id || rel.target_id == node_id;
            }),
        relations_.end()
    );
    
    nodes_.erase(it);
    return true;
}

Node* UniversalNodeManager::getNode(const std::string& node_id) {
    auto it = nodes_.find(node_id);
    if (it != nodes_.end()) {
        return &it->second;
    }
    return nullptr;
}

bool UniversalNodeManager::addRelation(const Relation& relation) {
    // 检查节点是否存在
    if (nodes_.find(relation.source_id) == nodes_.end() ||
        nodes_.find(relation.target_id) == nodes_.end()) {
        return false;
    }
    
    // 检查关系是否已存在
    for (const auto& rel : relations_) {
        if (rel.source_id == relation.source_id &&
            rel.target_id == relation.target_id &&
            rel.type == relation.type) {
            return false;
        }
    }
    
    relations_.push_back(relation);
    return true;
}

void UniversalNodeManager::discoverFeatures(Node& node) {
    switch (node.type) {
        case NODE_GIT_REPO:
            extractGitFeatures(node);
            break;
        case NODE_PACKAGE:
            // 提取包特征（版本、依赖、许可证等）
            node.features["version_stability"] = 0.8;
            node.features["popularity"] = 0.6;
            break;
        case NODE_AI_MODEL:
            // 提取AI模型特征
            node.features["accuracy"] = 0.9;
            node.features["efficiency"] = 0.7;
            break;
        default:
            break;
    }
}

void UniversalNodeManager::analyzeRelations(const Node& node) {
    // 基于特征相似性发现关系
    for (const auto& other_node : nodes_) {
        if (other_node.first == node.id) continue;
        
        double similarity = 0.0;
        for (const auto& feature : node.features) {
            if (other_node.second.features.count(feature.first)) {
                similarity += std::abs(feature.second - 
                    other_node.second.features.at(feature.first));
            }
        }
        
        if (similarity > 0.7) { // 相似度阈值
            Relation rel;
            rel.source_id = node.id;
            rel.target_id = other_node.first;
            rel.type = REL_SIMILARITY;
            rel.weight = similarity;
            addRelation(rel);
        }
    }
}

void UniversalNodeManager::calculateTokenWeights() {
    // 基于PageRank算法计算节点权重
    std::map<std::string, double> new_weights;
    const double damping = 0.85;
    
    for (const auto& node : nodes_) {
        double sum = 0.0;
        
        // 找到所有指向该节点的关系
        for (const auto& rel : relations_) {
            if (rel.target_id == node.first) {
                // 计算源节点的出度
                int out_degree = std::count_if(
                    relations_.begin(), relations_.end(),
                    [&](const Relation& r) { return r.source_id == rel.source_id; }
                );
                
                if (out_degree > 0) {
                    sum += nodes_[rel.source_id].weight / out_degree;
                }
            }
        }
        
        new_weights[node.first] = (1 - damping) + damping * sum;
    }
    
    // 更新权重
    for (auto& node : nodes_) {
        node.second.weight = new_weights[node.first];
    }
}

std::vector<std::string> UniversalNodeManager::findOptimalMirrors(const std::string& node_id) {
    std::vector<std::string> mirrors;
    
    auto* node = getNode(node_id);
    if (!node) return mirrors;
    
    // 基于特征相似性寻找镜像
    for (const auto& other_node : nodes_) {
        if (other_node.first == node_id) continue;
        
        if (other_node.second.type == node->type) {
            double similarity = 0.0;
            for (const auto& feature : node->features) {
                if (other_node.second.features.count(feature.first)) {
                    similarity += std::abs(feature.second - 
                        other_node.second.features.at(feature.first));
                }
            }
            
            if (similarity > 0.9) { // 高相似度视为镜像
                Relation mirror_rel;
                mirror_rel.source_id = node_id;
                mirror_rel.target_id = other_node.first;
                mirror_rel.type = REL_MIRROR;
                mirror_rel.weight = similarity;
                addRelation(mirror_rel);
                
                mirrors.push_back(other_node.first);
            }
        }
    }
    
    // 按权重排序
    std::sort(mirrors.begin(), mirrors.end(),
        [&](const std::string& a, const std::string& b) {
            return nodes_[a].weight > nodes_[b].weight;
        });
    
    return mirrors;
}

std::vector<std::string> UniversalNodeManager::findSimilarNodes(const std::string& node_id, double threshold) {
    std::vector<std::string> similar_nodes;
    
    auto* node = getNode(node_id);
    if (!node) return similar_nodes;
    
    for (const auto& rel : relations_) {
        if (rel.source_id == node_id && rel.type == REL_SIMILARITY && rel.weight >= threshold) {
            similar_nodes.push_back(rel.target_id);
        }
    }
    
    return similar_nodes;
}

bool UniversalNodeManager::saveToFile(const std::string& filename) {
    std::ofstream file(filename);
    if (!file.is_open()) {
        return false;
    }
    
    // 简单序列化实现
    file << "NODES:" << nodes_.size() << std::endl;
    for (const auto& node : nodes_) {
        file << node.first << "|" << node.second.type << "|" << node.second.uri << std::endl;
    }
    
    file << "RELATIONS:" << relations_.size() << std::endl;
    for (const auto& rel : relations_) {
        file << rel.source_id << "|" << rel.target_id << "|" << rel.type << "|" << rel.weight << std::endl;
    }
    
    file.close();
    return true;
}

void UniversalNodeManager::extractGitFeatures(Node& node) {
    // 实现Git特征提取
    node.features["has_readme"] = 0.8;
    node.features["active_development"] = 0.6;
    node.features["popularity"] = 0.7;
}

void UniversalNodeManager::analyzeGitRelations(Node& node) {
    // 实现Git关系分析
}

} // namespace unm
